package com.heima.app.gateway.filters;

import com.heima.app.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component

public class AuthorFilter implements GlobalFilter , Ordered {
    /**
     * 执行过滤的方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先获取请求对象和相应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否是登录请求
        if (request.getURI().getPath().contains("/login/login_auth")){
            //如果是登录请求，则放行
            return chain.filter(exchange);
        }
        //如果不是登录请求，则从请求头中获取token值
        String token = request.getHeaders().getFirst("token");
        //判断token是否有值
        if (token==null){
            //如果没有值，则返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果有值，则判断token值是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i==1 || i==2){
            //如果无效，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        //如果有效，则放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器优先级的方法。返回值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
